#!/usr/bin/python

from logger import logger

logger.debug("Logger successfully imported and initialized.")

import pygame
import rabbyt

logger.debug("Imported external modules successfully")

# Normal internal modules
from config import parser as config
from unit import Unit
import event

# Pseudomodules
import cfg
import state

logger.debug("Internal modules imported successfully")#


class Mouse:
	def __init__(self):
		self.x = self.y = self.bounding_radius = self.top = self.bottom = self.left = self.right = 0

class CamMovement:
	def __init__(self):
		self.x = self.y = self.mouse = self.keyboard_x = self.keyboard_y = 0
	def update(self):
		if not self.keyboard_x and not self.keyboard_y and not self.mouse:
			self.x = self.y = 0
		if -cfg.scrollspeed < self.x < cfg.scrollspeed:
			self.x *= cfg.scrollaccel
		if -cfg.scrollspeed < self.y < cfg.scrollspeed:
			self.y *= cfg.scrollaccel


class Camera:
	def __init__(self, xlimits, ylimits, zoomlimits):
		self.move = CamMovement()
	
		self.x = self.y = 0
		self.zoom = 1.0
		self.xlimits = xlimits
		self.ylimits = ylimits
		self.zoomlimits = zoomlimits
	
	def update(self):
		self.move.update()
		self.x += self.move.x / self.zoom
		self.y += self.move.y / self.zoom
#		logger.debug("camera X: " + str(self.x) + ", moving " + self.move.x + ".")
#		if self.zoom < self.zoomlimits[0]:
#			self.zoom = self.zoomlimits[0]
#		elif self.zoom > self.zoomlimits[1]:
#			self.zoom = self.zoomlimits[1]

def run():
####################################################################################
# Display/Pygame/Rabbyt setup
####################################################################################
	cfg.resolution = (config.getint("display", "xres"), config.getint("display", "yres"))
	cfg.fullscreen = config.getboolean("display", "fullscreen")
	pygame.init()
	if cfg.fullscreen:
		pygame.display.set_mode(cfg.resolution, pygame.OPENGL | pygame.DOUBLEBUF | pygame.FULLSCREEN)
	else:
		pygame.display.set_mode(cfg.resolution, pygame.OPENGL | pygame.DOUBLEBUF)
	pygame.display.set_caption("OpenRR")
	
	rabbyt.set_viewport(cfg.resolution, (0, 0) + cfg.resolution)
	rabbyt.set_default_attribs()
	FPS = config.getint("display", "fps")
	state.clock = pygame.time.Clock()
	
	state.mouse = Mouse()
####################################################################################
# Unit setup
####################################################################################
	cfg.utypes = {}
	units = config.getlist("main", "units")
	for utype in units:
		cfg.utypes[utype] = Unit(utype)
	
	rr = cfg.utypes["rockraider"].copy() # Copy method - slow? TODO benchmark.
	rr.wx = 100
	rr.wy = 100
	
	rr2 = cfg.utypes["rockraider"].copy()
	rr2.wx = 300
	rr2.wy = 100
	rr2.sprite.rot = 60
	
	state.units = []
	state.units.append(rr)
	state.units.append(rr2)
	state.selected = None

####################################################################################
# Other setup
####################################################################################

	cfg.minZoom = config.getfloat("control", "zoommin")
	cfg.maxZoom = config.getfloat("control", "zoommax")
	cfg.scrollborder = config.getint("main", "scrollborder")
	
	cfg.zoomspeed = config.getfloat("control", "zoomspeed")
	cfg.scrollspeed = config.getfloat("control", "scrollspeed")
	cfg.scrollaccel = config.getfloat("control", "scrollaccel")
	
	maxX = 2000
	maxY = 2000 # calculate from level size in future
	minX = -500
	minY = -500
	state.cam = Camera([minX, maxX], [minY, maxY], [cfg.minZoom, cfg.maxZoom])
	
	state.quit = False

####################################################################################
# Controls loading
####################################################################################
	
	keys = config.getlist("controls", "camleft")
	cfg.CAM_LEFT_KEYS = []
	for i in keys:
		cfg.CAM_LEFT_KEYS.append(int(i))
	
	keys = config.getlist("controls", "camright")
	cfg.CAM_RIGHT_KEYS = []
	for i in keys:
		cfg.CAM_RIGHT_KEYS.append(int(i))
	
	keys = config.getlist("controls", "camup")
	cfg.CAM_UP_KEYS = []
	for i in keys:
		cfg.CAM_UP_KEYS.append(int(i))

	keys = config.getlist("controls", "camdown")
	cfg.CAM_DOWN_KEYS = []
	for i in keys:
		cfg.CAM_DOWN_KEYS.append(int(i))


	
####################################################################################
# MAIN LOOP! All the action goes here :D
####################################################################################
	while not state.quit:
		rabbyt.clear((0.5, 0.2, 0))
		for u in state.units:
			u.draw(state.cam)
		pygame.display.flip()
		state.clock.tick(FPS)
		
		state.cam.update()
		
#		for e in pygame.event.get((pygame.KEYDOWN, pygame.KEYUP, pygame.MOUSEBUTTONDOWN, pygame.MOUSEMOTION)):
		for e in pygame.event.get():
			event.handle(e)

if __name__ == "__main__": # ACTUALLY RUN THE GAME :O
	run()
